package com.sky.aspect;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {


    @Pointcut("execution(* com.sky.mapper.*.*(..))&&@annotation(com.sky.annotation.AutoFill)")
    public void autoFill() {}

    @Before("autoFill()")
    public void before(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("前置通知");
        //获取实体对象
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        //获取注解
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value =autoFill.value();
        //获取参数
        Object[] args = joinPoint.getArgs();
        if (args.length==0){
            return;
        }
        Object arg = args[0];
        //统一赋值
        LocalDateTime now = LocalDateTime.now();
        Long empId = BaseContext.getCurrentId();
        if (value==OperationType.INSERT){
            Method setcreatetime= arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
            Method setcreateuser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
            Method setupdatetime= arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
            Method setupdateuser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
            //通过反射赋值
            log.info("操作类型: 插入");
            setcreatetime.invoke(arg,now);
            setcreateuser.invoke(arg,empId);
            setupdatetime.invoke(arg,now);
            setupdateuser.invoke(arg,empId);
            log.info("插入操作字段已填充");
        }else if (value==OperationType.UPDATE){
            log.info("操作类型: 更新");
            Method setupdatetime= arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
            Method setupdateuser = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
            //通过反射赋值
            setupdatetime.invoke(arg,now);
            setupdateuser.invoke(arg,empId);
            log.info("更新操作字段已填充");
        }

    }

}
